# -*- coding:utf-8 -*-
# author: lawaiter
# time: 2020/7/25
# brief: 这是搜索界面调用的函数

import requests, json

def search(text):

    """
    功能函数：搜索搜索框内输入内容，一般为歌手、歌曲名称
    :param text:
    :return:
    """

    # 根据搜索的内容不同，请求不同的搜索API接口
    if text[:2] == "歌手":
        search_url = "http://122.51.226.175:3000/search?type=100&keywords=" + text[3:]
        res1 = requests.get(search_url).json()
        # 解析输出
        res_parse1 = json.dumps(res1, indent=4, ensure_ascii=False, separators=(',', ': '))
        print(res_parse1)
        if json.loads(res_parse1)['result']['artistCount'] != 0:
            # json数据转换
            artists_id = str(json.loads(res_parse1)['result']['artists'][0]['id'])
            print("artists_id", artists_id)
            # 再围绕歌曲id进行该歌手的歌曲搜索
            res2 = requests.get("http://122.51.226.175:3000/artists?id=" + artists_id).json()
            res_parse2 = json.dumps(res2, indent=4, ensure_ascii=False, separators=(',', ': '))
            # json数据转换
            json_str = json.loads(res_parse2)['hotSongs']
            return json_str
        else:
            json_str = None
            return json_str
    elif text[:2] == "歌曲":
        search_url = "http://122.51.226.175:3000/search?type=1&keywords=" + text[3:]
        # 访问云主机，获取搜索结构
        res = requests.get(search_url).json()
        # 解析输出
        res_parse = json.dumps(res, indent=4, ensure_ascii=False, separators=(',', ': '))
        # json数据转换
        json_str = json.loads(res_parse)["result"]["songs"]
        return json_str
    # 搜索专辑的功能暂时不实现
    # elif text[:2] == "专辑":
    #     search_url = "http://122.51.226.175:3000/search?type=10&keywords=" + text[3:]
    else:
        search_url = ""

